import { login, getProfile, getUserDetailById } from '@/api/user'
import { resetRouter } from '@/router'
import { getToken, setToken, removeToken } from '@/utils/auth.js'
export default {
  namespaced: true,
  state: {
    userInfo: {},
    token: getToken()
  },
  mutations: {
    // 添加token
    setToken(state, newToken) {
      state.token = newToken
      setToken(newToken)
    },
    // 用户信息
    setUserInfo(state, userInfo) {
      state.userInfo = userInfo
    },
    // 删除用户信息
    reomveUserInfo(state) {
      state.token = ''
      removeToken()
      state.userInfo = {}
    }
  },
  actions: {
    async login(context, data) {
      const res = await login(data)
      context.commit('setToken', res.data)
    },
    logout(context) {
      // 删除token      // 删除userInfo
      context.commit('reomveUserInfo')
      // 重置路由
      resetRouter()
    },
    async getUserInfo(context) {
      const rs = await getProfile()
      const info = await getUserDetailById(rs.data.userId)
      context.commit('setUserInfo', { ...info.data, ...rs.data })
      return rs.data.roles.menus
    }
  }
}

